<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import {fetchAddBatch, fetchGetAllCategory, fetchGetAllHosp, fetchGetAllUser, fetchGetBatchDetail} from '@/service/api';
import { $t } from '@/locales';
import {
  batchStatusOptions,
} from '@/constants/business';

defineOptions({
  name: 'ManageBatchOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData: Api.SystemManage.Batch | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});
const hospRecordOptions = ref();
const userRecordOptions = ref();

const CategoryOptions = ref<CommonType.Option<string>[]>([]);
async function getCategoryOptions() {
  const { error, data } = await fetchGetAllCategory();

  if (!error) {
    const options = data.map(item => ({
      label: item.name,
      value: item.id
    }));
    CategoryOptions.value = [...options];
  }
}
const categories = ref(); // 使用 let 声明并初始化
async function getBatchDetail() {
  const { error, data } = await fetchGetBatchDetail(props.rowData.id);
  console.log(data);
  if (!error) {
    categories.value = data.categories; // 赋值给 categories
    console.log(categories);
  }
}

onMounted(async ()=>{
  const AllHosp =  await fetchGetAllHosp();
  const AllUser =  await fetchGetAllUser();
  const hostList = AllHosp.data.hospList
 const userList = AllUser.data.userList
 hospRecordOptions.value = hostList.map(hospital => ({
      label: hospital.hospName,
      value: hospital.hospId
    }));

  userRecordOptions.value = userList.map(user => ({
       label: user.userName,
       value: user.id
     }));


})


const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.batch.addBatch'),
    edit: $t('page.batch.editBatch')
  };
  return titles[props.operateType];
});
type Model = Pick<
  Api.SystemManage.Batch,
  'id' | 'name' |'status'| 'summarizeProblem' | 'summarizeHighlight' | 'summarizeNeedImprove' | 'note' | 'summarizePerson' | 'remark' | 'deleteFlag'|'startTime'|'endTime'
>;
const model = ref(createDefaultModel(props.rowData));
const modelPlus = ref({
  hospId: null,
  checkPersonId: null,
  categoryIds:[]
});
function createDefaultModel(rowData?: Api.SystemManage.Batch | null): Model {

  const defaultValues: Model = {
    id: '1',
    deleteFlag: 1,
    name: '',
    startTime: '2024-12-05 15:30:59',
    endTime: '2024-12-05 15:30:59',
    status: '0111',
    summarizeProblem: '',
    summarizeHighlight: '',
    summarizeNeedImprove: '',
    note: '',
    summarizePerson: '',
    remark: ''
  };
  return { ...defaultValues, ...rowData };
}
// 验证规则 hospName与deleteFlag必填
type RuleKey = Extract<keyof Model, 'name' | 'deleteFlag'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  deleteFlag: defaultRequiredRule,

};

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  console.log(props.rowData);
  try {
    // 验证表单
    await validate();
    // 根据操作类型构造请求参数
    const params = {
      ...model.value,...modelPlus.value
    };
    let response;
    const { id, ...restParams } = params;
    // 根据操作类型调用不同的接口
    switch (props.operateType) {
      case 'add':
        // 调用添加接口
        console.log(params);
        response = await fetchAddBatch(restParams);
        break;
      case 'edit':
        console.log(params);
        // response = await fetchEditBatch(params);
        break;
      default:
        throw new Error('未知的操作类型');
    }
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.updateSuccess'));
    // 关闭抽屉
    closeDrawer();
    // 触发父组件的事件，通知更新表格数据
    emit('submitted');
  } catch (error) {
    // 捕获可能的错误
    console.error('Submit Error:', error);
    // 根据错误类型显示不同的提示
    const errorMessage = $t('common.operationFailed');
    window.$message?.error(errorMessage);
  }
}
watch(visible, () => {
  if (visible.value) {
    getBatchDetail();
    handleInitModel();
    restoreValidation();
    getCategoryOptions();

    // getRoleOptions();
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <template v-if="props.operateType === 'edit'">
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem :label="$t('page.batch.name')">
            <NInput v-model:value="model.name" :placeholder="$t('page.batch.name')" :readonly="true"/>
          </NFormItem>
          <NFormItem :label="$t('page.batch.note')">
            <NInput v-model:value="model.note" :placeholder="$t('page.batch.note')" />
          </NFormItem>
          <NFormItem :label="$t('page.batch.remark')">
            <NInput v-model:value="model.remark" :placeholder="$t('page.batch.remark')" />
          </NFormItem>
          <NCollapse>
            <NCollapseItem
              v-for="(category, index) in categories"
              :key="index"
              :title="`${category.categoryName}`"
            >
              <template #header-extra>
                {{ `${category.categoryScore}分` }}
              </template>
              <NCollapse>
                <NCollapseItem
                  v-for="(area, areaIndex) in category.areas"
                  :key="areaIndex"
                  style="margin-bottom: 10px;"
                  :title="`${area.areaName}`"
                >
                  <template #header-extra>
                    {{ `${area.areaScore}分` }}
                  </template>
                  <NCollapse>
                    <NCollapseItem
                      v-for="(item, itemIndex) in area.items"
                      :key="itemIndex"
                      :title="`${item.itemName}`"
                      arrow-placement="right"
                    >
                      <template #header-extra>
                        {{ `${item.itemScore}分` }}
                      </template>
                      <NText v-if="item.remark !== 'null'" type="error">
                        问题留痕：{{ item.remark }}
                      </NText>
<!--                      <div v-if="item.remark !== 'null'">-->
<!--                        问题留痕：{{ item.remark }}-->
<!--                      </div>-->
                    </NCollapseItem>
                  </NCollapse>
                </NCollapseItem>
              </NCollapse>
            </NCollapseItem>
          </NCollapse>
        </NForm>
      </template>
      <template v-else-if="props.operateType === 'add'">
        <NForm ref="formRef" :model="model" :rules="rules">
          <NFormItem :label="$t('page.batch.name')">
            <NInput v-model:value="model.name" :placeholder="$t('page.batch.name')" />
          </NFormItem>


          <NFormItem :label="$t('医院')">
            <NSelect
              v-model:value="modelPlus.hospId"
              :options="hospRecordOptions"
            />
          </NFormItem>
          <NFormItem :label="$t('检查人员')">
            <NSelect
              v-model:value="modelPlus.checkPersonId"
              :options="userRecordOptions"
            />
          </NFormItem>
          <NFormItem :label="$t('考核类别（多选）')">
            <NSelect
            multiple
              v-model:value="modelPlus.categoryIds"
              :options="CategoryOptions"
              :placeholder="$t('page.check.area.form.categoryId')"
            />
          </NFormItem>


          <NFormItem :label="$t('page.batch.startTime')">
            <NDatePicker
              v-model:formatted-value="model.startTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.startTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.endTime')">
            <NDatePicker
              v-model:formatted-value="model.endTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('page.batch.endTime')"
              type="datetime"
            />
          </NFormItem>
          <NFormItem :label="$t('page.batch.status')">
            <NRadioGroup v-model:value="model.status">
              <NRadio v-for="item in batchStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
            </NRadioGroup>
          </NFormItem>
        </NForm>
      </template>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
